import logging

from flask import render_template, make_response, request
from flask_restful import Resource, reqparse
from app.commons.check_token import checkIfLogin
import urllib.parse

from app.commons.db import db
from app.commons.ma import ma
from app.commons.pagination import get_page
from app.models.buff_stock.buyer_stock import BuyerStockInfo
from app.service.csgo_stock.csgo_stock import GetTotalStock, GetBuyerStockWithRent, set_buff_cookie, \
    get_last_update_time, get_current_price_by_items, upsert_proxy_token
from enum import Enum

from app.utils.update_price import get_current_price_by_items_once

parser = reqparse.RequestParser(trim=True)


class StockReqType(Enum):
    GetOption = 1
    ViewList = 2
    InsertItem = 3
    InsertCookie = 4
    GetMtime = 5
    GetPrice = 6
    UpsertProxyToken = 7


class StockRequestArgs(ma.Schema):
    data = ma.String()
    page = ma.Integer()
    limit = ma.Integer()
    type = ma.Integer()
    date = ma.String()


class CsgoStockView(Resource):
    def get(self):
        try:
            cookie = urllib.parse.unquote(str(request.cookies.get('pj_login')))
            query_args = StockRequestArgs().dump(request.args)
            request_type = int(query_args["type"])
            if request_type == StockReqType.GetOption.value:
                result = GetTotalStock()
                return {"code": 0, "success": "true", "msg": "", "count": len(result), "data": result}
            elif request_type == StockReqType.ViewList.value:
                username = checkIfLogin(cookie)
                if username:
                    try:
                        page = int(query_args["page"])
                        limit = int(query_args["limit"])
                    except:
                        page = 1
                        limit = 15
                    data = GetBuyerStockWithRent(username)
                    data, total_size = get_page(page, limit, data)
                    return {"code": 0, "success": "true", "msg": "", "count": total_size, "data": data}
        except:
            return {"err_msg": 404}

    def post(self):
        try:
            cookie = urllib.parse.unquote(str(request.cookies.get('pj_login')))
            username = checkIfLogin(cookie)
            if username:
                recv_data = request.get_json()
                if recv_data["type"] == StockReqType.InsertItem.value:
                    stock_info = BuyerStockInfo(username=username, item_id=recv_data["item_id"], price=recv_data["price"])
                    db.session.add(stock_info)
                    db.session.commit()
                    db.session.close()
                    get_current_price_by_items_once(stock_items=[recv_data["item_id"]],only_one=True,need_proxy=True)
                    # get_current_price_by_items([recv_data["item_id"]],only_one=True)
                elif recv_data["type"] == StockReqType.InsertCookie.value:
                    set_buff_cookie(recv_data["cookie"])
                elif recv_data["type"] == StockReqType.GetPrice.value:
                    try:
                        get_current_price_by_items_once(need_proxy=True)
                    except:
                        return {"success": "false"}
                elif recv_data["type"] == StockReqType.UpsertProxyToken.value:
                    upsert_proxy_token(recv_data["token"])
                return {"success": "true"}
            else:
                return {"success": "false", "err_msg": "no login"}
        except:
            logging.warning("fail adding stocklist")
            return {"success": "false"}
